package com.jifen.agent.service;

import com.alibaba.fastjson.JSONObject;
import com.jifen.agent.dao.SmarketJifenDetailDao;
import com.jifen.agent.entity.AgentBill;
import com.jifen.agent.entity.SmarketAdd;
import com.jifen.agent.entity.SmarketJifenDetail;
import com.jifen.agent.vo.AgentBillVo;
import com.jifen.agent.vo.MarketVo;
import com.jifen.agent.vo.MchVo;
import com.jifen.common.MyException;
import com.jifen.config.Global;
import com.jifen.constant.CommonConstant;
import com.jifen.constant.ErrorCode;
import com.jifen.mch.dao.MchDao;
import com.jifen.mch.dao.MchJifenDetailDao;
import com.jifen.mch.entity.Mch;
import com.jifen.mch.entity.MchAdd;
import com.jifen.mch.vo.MchParam;
import com.jifen.user.dao.UserDao;
import com.jifen.user.entity.User;
import com.jifen.user.service.UserService;
import com.jifen.user.vo.TokenUserVo;
import com.jifen.user.vo.UserJifenDetailVo;
import com.jifen.utils.DateUtils;
import com.jifen.utils.DigestsUtils;
import com.jifen.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class AgentService {

    @Autowired
    UserService userService;
    @Autowired
    SmarketJifenDetailDao smarketJifenDetailDao;
    @Autowired
    MchDao mchDao;
    @Autowired
    UserDao userDao;
    @Autowired
    MchJifenDetailDao mchJifenDetailDao;

    /**
     * 我的超市
     * @param param
     * @return
     */
    public Map<String, Object> getMySmarket(MchParam param){
        TokenUserVo tokenUser = userService.getTokenUser(param.getToken());
        param.setId(tokenUser.getId());
        param.setPageNo((param.getPageNo() - 1) * param.getPageSize());
        Map<String, Object> map = new HashMap<>();
        List<MarketVo> list = mchDao.getMarketByAgent(param);
        for (int i = 0; i < list.size(); i++) {
            param.setType(1);
            param.setDate(DateUtils.formatDate("yyyy-MM-dd"));
            param.setId(list.get(i).getId());
            Double todayInJifen = smarketJifenDetailDao.sumBillJifenByDay(param);
            list.get(i).setTodayInJifen(todayInJifen!=null?todayInJifen.intValue():0);
        }
        map.put("smarkets", list);
        Double outJifen = mchJifenDetailDao.sumAgentTotalOutJifen(tokenUser.getId());
        Double inJifen = smarketJifenDetailDao.sumJifenByTotal(1, tokenUser.getId());
        map.put("outJifen", outJifen!=null?outJifen:0);
        map.put("inJifen", inJifen!=null?inJifen:0);
        return map;
    }

    /**
     * 我的商家
     * @param param
     * @return
     */
    public List<MchVo> getMyMch(MchParam param){
        TokenUserVo tokenUser = userService.getTokenUser(param.getToken());
        param.setId(tokenUser.getId());
        param.setPageNo((param.getPageNo() - 1) * param.getPageSize());
        List<MchVo> list = mchDao.getMchByAgent(param);
        for (int i = 0; i < list.size(); i++) {
            param.setType(1);
            param.setId(list.get(i).getId());
            param.setDate(DateUtils.formatDate("yyyy-MM-dd"));
            Double todayInJifen = mchJifenDetailDao.sumJifenByDay(param);
            param.setDate(DateUtils.formatDate("yyyy-MM"));
            Double monthInJifen = mchJifenDetailDao.sumJifenByMonth(param);
            Double totalInJifen = mchJifenDetailDao.sumJifenByTotal(param);
            list.get(i).setTodayInJifen(todayInJifen!=null?todayInJifen.intValue():0);
            list.get(i).setMonthInJifen(monthInJifen!=null?monthInJifen.intValue():0);
            list.get(i).setTotalInJifen(totalInJifen!=null?totalInJifen.intValue():0);
        }
        return list;
    }

    /**
     * 超市积分明细
     * @param param
     * @return
     */
    public Map<String, Object> getSmarketJifenDetail(MchParam param){
        TokenUserVo tokenUser = userService.getTokenUser(param.getToken());
        Map<String, Object> map = new HashMap<>();
        AgentBillVo billVo = new AgentBillVo();
        if(param.getQtype()==0) {
            param.setDate(DateUtils.formatDate("yyyy-MM-dd"));
        }
        // 总支出积分
        param.setType(2);
        Double totalJifen = smarketJifenDetailDao.sumBillJifenByDay(param);
        if (totalJifen != null) {
            billVo.setOutJifen(totalJifen);
        }
        // 总收入积分
        param.setType(1);
        totalJifen = smarketJifenDetailDao.sumBillJifenByDay(param);
        if (totalJifen != null) {
            billVo.setInJifen(totalJifen);
        }
        map.put("total", billVo);
        if(param.getQtype()==0){
            param.setDate(null);
        }
        param.setPageNo((param.getPageNo() - 1) * param.getPageSize());
        List<SmarketJifenDetail> detailList = smarketJifenDetailDao.selectPage(param);
        List<UserJifenDetailVo> voList = new ArrayList<>();
        for (int i = 0; i < detailList.size(); i++) {
            UserJifenDetailVo vo = new UserJifenDetailVo();
            BeanUtils.copyProperties(detailList.get(i), vo);
            vo.setDate(DateUtils.formatDate(detailList.get(i).getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            voList.add(vo);
        }
        map.put("details", voList);
        return map;
    }

    /**
     * 添加商家
     * @param add
     * @param add
     */
    @Transactional
    public void addMch(MchAdd add){
        TokenUserVo tokenUser = userService.getTokenUser(add.getToken());
        User agent = userDao.selectByPrimaryKey(tokenUser.getId());
        if(agent.getIsAgent()==1) {
            Mch mch = new Mch();
            mch.setName(add.getName());
            mch.setIndustry(add.getIndustry());
            User user = userDao.getByMobile(add.getAdminMobile());
            if(user!=null){
                if(user.getIsMch()==1){
                    throw new MyException(ErrorCode.USER_ALREADY_MCH);
                }
                mch.setUid(user.getId());
                User adminUser = new User();
                adminUser.setId(user.getId());
                adminUser.setIsMch(1);
                userDao.updateByPrimaryKeySelective(adminUser);
            }else{
                // 自动注册
                user = new User();
                user.setMobile(add.getAdminMobile());
                user.setIsMch(1);
                user.setPassword(DigestsUtils.md5( "e10adc3949ba59abbe56e057f20f883e" + CommonConstant.SALT));
                user.setCreateTime(DateUtils.getDate());
                userDao.insertSelective(user);
                // 发送短信
                JSONObject param = new JSONObject();
                param.put("password", "123456");
                SmsUtils.sendSms(add.getAdminMobile(), "SMS_169102553", param);
            }
            mch.setUid(user.getId());
            mch.setAgentId(tokenUser.getId());
            mch.setPhone(add.getAdminMobile());
            mch.setContactPerson(add.getContactPerson());
            mch.setCreateTime(DateUtils.getDate());
            mchDao.insertSelective(mch);
        }else{
            throw new MyException(ErrorCode.NOT_ADD_MCH);
        }
    }

    /**
     * 添加超市
     * @param add
     */
    @Transactional
    public void addSmarket(SmarketAdd add){
        TokenUserVo tokenUser = userService.getTokenUser(add.getToken());
        User agent = userDao.selectByPrimaryKey(tokenUser.getId());
        if(agent.getIsAgent()==1) {
            Mch mch = new Mch();
            mch.setName(add.getName());
            mch.setType(2);
            User user = userDao.getByMobile(add.getAdminMobile());
            if(user!=null){
                if(user.getIsAgent()==1) {
                    throw new MyException(ErrorCode.ADMIN_NOT_AGENT);
                }else if(user.getIsAdmin()==1) {
                    throw new MyException(ErrorCode.ADMIN_ALREADY_BIND);
                }
                mch.setMuid(user.getId());
                User adminUser = new User();
                adminUser.setId(user.getId());
                adminUser.setIsAdmin(1);
                userDao.updateByPrimaryKeySelective(adminUser);
            }
            mch.setAgentId(tokenUser.getId());
            mch.setPhone(add.getPhone());
            mch.setIntroduce(add.getIntroduce());
            mch.setAddress(add.getAddress());
            mch.setCreateTime(DateUtils.getDate());
            if(StringUtils.isNotBlank(add.getSlidePic())) {
                String[] slidePics = add.getSlidePic().split(",");
                if(slidePics!=null && slidePics.length>0) {
                    mch.setHead(slidePics[0]);
                }
                mch.setSlidePic(add.getSlidePic());
            }
            mchDao.insertSelective(mch);
        }else{
            throw new MyException(ErrorCode.NOT_ADD_SMARKET);
        }
    }
    /**
     * 超市账单
     * @param param
     * @return
     */
    public Map<String, Object> smarketBill(MchParam param){
        TokenUserVo tokenUser = userService.getTokenUser(param.getToken());
        Map<String, Object> map = new HashMap<>();
        AgentBillVo billVo = new AgentBillVo();
        // 总支出积分
        param.setType(2);
        Double totalJifen = smarketJifenDetailDao.sumBillJifenByMonth(param);
        if(totalJifen!=null) {
            billVo.setOutJifen(totalJifen);
        }
        // 总收入积分
        param.setType(1);
        totalJifen = smarketJifenDetailDao.sumBillJifenByMonth(param);
        if(totalJifen!=null) {
            billVo.setInJifen(totalJifen);
        }
        map.put("bill", billVo);
        String curDate = param.getDate()+"-"+DateUtils.getCurDateDay();
        List<String> dayList = DateUtils.getDayListOfMonth(curDate);
        List<AgentBillVo> daysBill = new ArrayList<>();
        param.setType(2);
        param.setDates(dayList);
        List<AgentBill> outBills = smarketJifenDetailDao.sumBillJifenByDays(param);
        param.setType(1);
        param.setDates(dayList);
        List<AgentBill> inBills = smarketJifenDetailDao.sumBillJifenByDays(param);
        for (int i = 0; i < dayList.size(); i++) {
            String days = dayList.get(i);
            AgentBill outBill = null;
            AgentBill inBill = null;
            param.setDate(days);
            param.setType(1);
            Double dayTotalInJifen = smarketJifenDetailDao.sumBillJifenByDay(param);
            param.setType(2);
            Double dayTotalOutJifen = smarketJifenDetailDao.sumBillJifenByDay(param);
            for (int a = 0; a < outBills.size(); a++) {
                outBill = outBills.get(a);
                if(DateUtils.parse(outBill.getDate(), "yyyy-MM-dd").equals(days)){
                    break;
                }else{
                    outBill = null;
                }
            }
            for (int b = 0; b < inBills.size(); b++) {
                inBill = inBills.get(b);
                if(DateUtils.parse(inBill.getDate(), "yyyy-MM-dd").equals(days)){
                    break;
                }else{
                    inBill = null;
                }
            }
            AgentBillVo dayBill = new AgentBillVo();
            dayBill.setDate(days);
            if(outBill!=null) {
                dayBill.setOutJifen(dayTotalOutJifen!=null?dayTotalOutJifen:0);
            }
            if(inBill!=null) {
                dayBill.setInJifen(dayTotalInJifen!=null?dayTotalInJifen:0);
            }
            if(dayBill.getOutJifen()!=0 || dayBill.getInJifen()!=0){
                daysBill.add(dayBill);
            }
        }
        map.put("daysBill", daysBill);
        return map;
    }

    /**
     * 修改超市
     * @param smarket
     */
    public void modifySmarket(SmarketAdd smarket){
        TokenUserVo tokenUser = userService.getTokenUser(smarket.getToken());
        Mch mch = mchDao.selectByPrimaryKey(smarket.getId());
        if(mch.getAgentId().equals(tokenUser.getId())||mch.getMuid().equals(tokenUser.getId())) {
            Mch info = new Mch();
            info.setId(smarket.getId());
            info.setName(smarket.getName());
            info.setPhone(smarket.getPhone());
            info.setAddress(smarket.getAddress());
            info.setSlidePic(smarket.getSlidePic());
            info.setIntroduce(smarket.getIntroduce());
            User user = userDao.getByMobile(smarket.getAdminMobile());
            if(user!=null){
                if(user.getIsAgent()==1) {
                    throw new MyException(ErrorCode.ADMIN_NOT_AGENT);
                }else if(user.getIsAdmin()==1) {
                    throw new MyException(ErrorCode.ADMIN_ALREADY_BIND);
                }
                info.setMuid(user.getId());
                User adminUser = new User();
                adminUser.setId(user.getId());
                adminUser.setIsAdmin(1);
                userDao.updateByPrimaryKeySelective(adminUser);
            }
            if(StringUtils.isNotBlank(smarket.getSlidePic())) {
                String[] slidePics = smarket.getSlidePic().split(",");
                if(slidePics!=null && slidePics.length>0) {
                    info.setHead(slidePics[0]);
                }
            }
            mchDao.updateByPrimaryKeySelective(info);
        }
    }

}
